﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace ObviousCode.UI.Aspect
{
    public class LasooStateHandler
    {
        public bool IsLasooing { get; private set; }

        public bool IsLasooEnding { get; private set; }
        public bool IsLasooStarting { get; private set; }

        public PointF LasooStart { get; set; }
        public PointF LasooEnd { get; set; }

        public PointF LastMouseDownOnSurfaceLocation { get; private set; }

        public LasooStateHandler()
        {
            IsLasooing = false;
            IsLasooEnding = false;
            IsLasooStarting = false;
        }

        public void RegisterMouseDownOnSurface(MouseEventArgs e)
        {
            IsLasooEnding = false;
            LastMouseDownOnSurfaceLocation = e.Location;
            IsLasooStarting = true;
        }

        public void RegisterMouseMove(MouseEventArgs e)
        {
            IsLasooEnding = false;
            if (!IsLasooing && !IsLasooStarting) return;

            if (IsLasooStarting)
            {
                float offsetX = Math.Abs(LastMouseDownOnSurfaceLocation.X - e.Location.X);
                float offsetY = Math.Abs(LastMouseDownOnSurfaceLocation.Y - e.Location.Y);

                if (offsetX > .5 && offsetY > .5)
                {
                    BeginLasoo(LastMouseDownOnSurfaceLocation);
                }
            }
            
            if (IsLasooing)
            {
                ContinueLasoo(e.Location);
            }
        }

        public void RegisterMouseUp(MouseEventArgs e)
        {
            IsLasooStarting = false;

            if (!IsLasooing) return;
            EndLasoo(e.Location);                
            
        }

        private void BeginLasoo(PointF start)
        {            
            LasooStart = new PointF(start.X, start.Y);
            LasooEnd = LasooStart;

            IsLasooStarting = false;
            IsLasooing = true;
        }

        private void ContinueLasoo(Point point)
        {
            LasooEnd = point;
        }

        private void EndLasoo(Point end)
        {         
            IsLasooing = false;
            IsLasooEnding = true;
        }

        public RectangleF LasooBounds
        {
            get
            {
                if (!IsLasooing) return new RectangleF(0f, 0f, 0f, 0f);

                float startX = Math.Min(LasooStart.X, LasooEnd.X);
                float startY = Math.Min(LasooStart.Y, LasooEnd.Y);
                float endX = Math.Max(LasooStart.X, LasooEnd.X);
                float endY = Math.Max(LasooStart.Y, LasooEnd.Y);

                return new RectangleF(startX, startY, endX - startX, endY - startY);
            }
        }
    }
}
